#include "FMain.h"
#include "FManager.h"
#include "Constants.h"


using namespace Osp::Base;
using namespace Osp::Ui;
using namespace Osp::Ui::Controls;

FMain::FMain(void)
{
  this->__pBtnPlayGame = null;
	this->__pCanvas      = null;
}

FMain::~FMain(void)
{
  CHECK_AND_DELETE(this->__pCanvas);
}

bool
FMain::Initialize()
{
	// Construct an XML form
	Construct(L"IDF_FMAIN");

	return true;
}

result
FMain::OnInitializing(void)
{
	result r = E_SUCCESS;

	// TODO: Add your initialization code here

	// Get a button via resource ID
	__pBtnPlayGame = static_cast<Button *>(GetControl(L"IDC_BTN_PLAY_GAME"));
	if (__pBtnPlayGame != null)
	{
		__pBtnPlayGame->SetActionId(IDC_BTN_PLAY_GAME);
		__pBtnPlayGame->AddActionEventListener(*this);
	}

	__pBtnExit = static_cast<Button *>(GetControl(L"IDC_BTN_EXIT"));
	if (__pBtnExit != null)
	{
		__pBtnExit->SetActionId(IDC_BTN_EXIT);
		__pBtnExit->AddActionEventListener(*this);
	}

	return r;
}

result
FMain::OnTerminating(void)
{
	result r = E_SUCCESS;

	// TODO: Add your termination code here

	return r;
}

void
FMain::OnActionPerformed(const Osp::Ui::Control& source, int actionId)
{
	switch(actionId)
	{
	  case IDC_BTN_PLAY_GAME :
		{
		  FManager::GetInstance()->SendUserEvent(FManager::ID_REQUEST_FORM_GAME, null);
		}
		break;
	  case IDC_BTN_EXIT     :
		{
		  Osp::App::Application::GetInstance()->GetInstance()->Terminate();
		}
		break;
	  default:
		break;
	}
}

result
FMain::OnDraw(void)
{
  if (this->__pCanvas == null)
  {
	  this->__pCanvas  = GetCanvasN();
  	TryReturn(this->__pCanvas != null, E_FAILURE, "FMain.OnDraw");
  }

  return DrawView();
}

void
FMain::SetFormBackground()
{
	Image image;
	image.Construct();
	Bitmap* pFormBG = image.DecodeN("/Res/imgs/main_background01.png", BITMAP_PIXEL_FORMAT_RGB565, SCREEN_WIDTH, SCREEN_HEIGHT);
	this->__pCanvas->DrawBitmap(Point(0, 0), *pFormBG);
	CHECK_AND_DELETE(pFormBG);
}

result
FMain::DrawView(void)
{
  result r = E_FAILURE;

  if (this->__pCanvas)
  {
	  SetFormBackground();
	  r = E_SUCCESS;
  }

  return r;
}

